//
//  JHSearchBar.swift
//  JHSinaWeibo
//
//  Created by apple on 16/5/21.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class JHSearchBar: UIView {
//提供加载NIB文件的“类方法”
    //在func前加“class”就是类方法
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var searchTF: UITextField!
    @IBOutlet weak var rightConstraint: NSLayoutConstraint!

   class func loadSearchBar() -> JHSearchBar{
    let searchView = NSBundle.mainBundle().loadNibNamed("JHSearchBar", owner: nil, options: nil).last as! JHSearchBar
    
    return searchView
   }
    //在awakeFromNib做初始化设置
    override func awakeFromNib() {
        self.bounds.size.width = ScreenWidth
        //文本输入框有leftView
        searchTF.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        //设置显示模式
        searchTF.leftViewMode = .Always
        //修改frame
        searchTF.leftView?.frame = CGRect(x:0,y: 0,width: 40,height: 40)
        //设置视图的显示模式
        searchTF.leftView?.contentMode = .Center
    }
    
    @IBAction func textFieldBeginEditing(sender: AnyObject) {
        //修改约束
        //系统默认的动画事件
        UIView.animateWithDuration(0.5){
        self.rightConstraint.constant = self.cancelBtn.bounds.width
            //提前强制刷新视图
        self.layoutIfNeeded()
        }
        
        
    }
    //关联 取消按钮点击事件 取消textField 的编辑状态
    @IBAction func cancelBtnDidClick(sender: AnyObject) {
        
        //修改约束
        self.rightConstraint.constant = 0
        UIView.animateWithDuration(0.5){
        self.layoutIfNeeded()
        
        }
        //编辑状态
        self.endEditing(true)
    }
}
